from flask import render_template,request,redirect,flash,url_for
from app import app
from models import User,Post
from forms import RegisterForm,LoginForm
from exts import bcrypt,db
from flask_login import login_user,login_required,current_user,logout_user


@app.route("/register", methods=('GET', 'POST'))
# @login_required
def Register():
    if current_user.is_authenticated:
        return redirect("/") 
    myForm=RegisterForm()
    if myForm.validate_on_submit():
        password=bcrypt.generate_password_hash(myForm.password.data)
        newuser=User(username=myForm.username.data,password=password,email=myForm.email.data)
        db.session.add(newuser)
        db.session.commit()    
        flash("register ok!", category='success')   
        return redirect(url_for("loginform")) 
    return render_template("register.html",form=myForm)

@app.route("/loginform",methods=["GET","POST"])
def loginform():
    if current_user.is_authenticated:
        return redirect("/")  
    myForm=LoginForm()
    if myForm.validate_on_submit():        
        username=myForm.username.data
        remember=myForm.remember.data
        user=User.query.filter_by(username=username).first()
        if user and bcrypt.check_password_hash(user.password,myForm.password.data):
            login_user(user,remember=remember)
            flash("login ok!", category='success')
            if request.args.get('next'):  #记录next，下一跳,如果有
                nextpage=request.args.get("next")
                return redirect(nextpage)
            return redirect("/")   
        else:
            flash("login error!", category='danger')

    return render_template("loginform.html",form=myForm)

@app.route("/logout")
@login_required
def Logout():
    logout_user()
    return redirect(url_for("loginform")) 



# @app.route("/login__",methods=["GET","POST"])
# def Login():
#     res={
#         "code":400,
#         "status":"ok",
#         "success":False
#     }
#     if request.method=="POST":
#         user=User.query.filter_by(username=request.form['username']).first()
#         if not user:
#             res['code']=404
#             res["status"]='no username'
#             res['success']=False
#             flash("no username", category='alert alert-danger')
#             # return json.dumps(res)
#         else:
#             if  user.username==request.form['username'] and bcrypt.check_password_hash(user.password,request.form['password']):
#                 res['code']=400
#                 res['status']="ok"
#                 res['success']=True
#                 return redirect("/")
#             else:
#                 res["code"]=401
#                 res["status"]="wrong username and password."
#                 res['success']=False
#                 flash("wrong username and password.", category='alert alert-danger')
#                 # return json.dumps(res)


#     return render_template("login.html",Title="Login")